package com.iceberg;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class AlgorithmVisualizer {
    private Circle[] circles;
    private AlgorithmFrame algorithmFrame;
    private boolean isAnimated = true;

    public AlgorithmVisualizer(int sceneWidth, int sceneHeight, int N){
        circles = new Circle[N];

        int R = 50;

        for (int i = 0; i < circles.length; i++){
            int x = (int)(Math.random()*(sceneWidth - 2*R)) + R;
            int y = (int)(Math.random()*(sceneHeight - 2*R)) + R;
            int vx = (int)(Math.random()*11) - 5;
            int vy = (int)(Math.random()*11) - 5;
            circles[i] = new Circle(x, y, R, vx, vy);
        }

        EventQueue.invokeLater(() ->{
            algorithmFrame = new AlgorithmFrame("Welcome", sceneWidth, sceneHeight);
            algorithmFrame.addKeyListener(new AlgorithmKeyListener());
            algorithmFrame.addMouseListener(new AlgorithmMouseListener());
            new Thread(() -> {
                run();
            }).start();
        });
    }

    private void run(){
        while (true){
            algorithmFrame.render(circles);
            AlgorithmVisualHelper.pause(20);
            if (isAnimated){
                for (Circle circle: circles){
                    circle.move(0, 0, algorithmFrame.getCanvasWidth(), algorithmFrame.getCanvasHeight());
                }
            }
        }
    }

    private class AlgorithmKeyListener extends KeyAdapter{

        @Override
        public void keyReleased(KeyEvent event){
            if (event.getKeyChar() == ' '){
                isAnimated = !isAnimated;
            }
        }
    }

    private class AlgorithmMouseListener extends MouseAdapter{

        @Override
        public void mousePressed(MouseEvent event){
            event.translatePoint(0, -(algorithmFrame.getBounds().height - algorithmFrame.getCanvasHeight()));
            Point point = event.getPoint();
            for (Circle circle: circles){
                if (circle.contain(point)){
                    circle.isFilled = !circle.isFilled;
                }
            }
        }

    }
}
